import numpy as np
import matplotlib.pyplot as plt
from next_level.Finance_Data.stock_load import load_stock

def do_simple_plot(stock_df,name_str):
    '''绘图函数
    绘制收盘价图形
    '''
    makeplot_rewrite(stock_df,'Close','closing price')
    plt.title(name_str + 'Stock Price')
    plt.show()


def do_highlow_plot(stock_df,name_str):
    '''绘制最高/最低价图形函数
    绘制股票的最高价和最低价图形
    '''
    makeplot_rewrite(stock_df,'High','daily highs')
    makeplot_rewrite(stock_df, 'Low','daily lows')
    plt.title('High/Low Prices for ' + name_str)
    plt.show()


def do_volume_subplot(stock_df,name_str):
    '''绘制交易量子图函数
    绘制收盘价和交易量子图
    '''
    plt.subplot(2, 1, 1)                     # 绘制上面一半图形
    makeplot_rewrite(stock_df, 'Close', 'price')
    plt.title(name_str + ' Price/Volume')
    plt.subplot(2, 1, 2)                     # 绘制下面一半图形
    makeplot_rewrite(stock_df, 'Volume', 'volume')
    plt.show()


def do_movingavg_plot(stock_df,name_str,revolution=180):
    '''绘制移动平均函数
    绘制价格图形和区间为 360 天的移动平均线
    '''
    makeplot_rewrite(stock_df,'Close','closing price')
    makeplot_rewrite(stock_df,'Close','360 day average',revolution)
    plt.title(name_str + 'Stock Price')
    plt.show()


def makeplot_rewrite(stock_df,field,my_str,avg=0):
    '''做重复性计算'''
    column = getattr(stock_df,field)

    if avg:    # 当 avg不为0时绘制
        column = column.rolling(avg,min_periods=1).mean()   # 绘制移动平均线

    column = np.array(column,dtype='float')
    date = np.array(stock_df.Date)
    plt.plot(date, column, label=my_str)
    plt.legend()


if __name__ == '__main__':
    name_str = 'GOOGL'
    stock_df = load_stock(name_str)
    do_movingavg_plot(stock_df,name_str)
    do_simple_plot(stock_df,name_str)
    do_volume_subplot(stock_df,name_str)
    do_highlow_plot(stock_df,name_str)
